﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Configuration;
using System.Data.OracleClient;
using System.Xml;

namespace MESNonconforming
{
   public  class SendNonconformingData
    {

       public void RunNonconformingSync()
       {
           DataTable mydt = GetNonconforming();
           if (mydt == null || mydt.Rows.Count <= 0)
           {
             //  LogHelp.WriteLog("没有可处理的不合格品审理记录");
           }

           Dictionary<string, string> strList;

           ERPService.PS_SAPServicesHttpService sap = new ERPService.PS_SAPServicesHttpService();
           foreach (DataRow dr in mydt.Rows)
           {

            //   LogHelp.WriteLog("处理不合格平审理开始" + dr["CONTAINERID"].ToString());
               strList = new Dictionary<string, string>();

               strList.Add("ZQMMES-MATNR", dr["MATNR"].ToString());//物料号
               strList.Add("ZQMMES-FERTAUFNR", dr["FERTAUFNR"].ToString());//	   生产订单号
               strList.Add("ZQMMES-ZMESGX", dr["ZMESGX"].ToString());//MES工序
               strList.Add("ZQMMES-ZMESGXTXT", dr["ZMESGXTXT"].ToString());//工序描述

               if (dr["UVORN"].ToString() == "0000")
                   strList.Add("ZQMMES-UVORN", "0001");//子工序
               else
               strList.Add("ZQMMES-UVORN", dr["UVORN"].ToString());//子工序
               strList.Add("ZQMMES-ZLTXA1", dr["ZLTXA1"].ToString());//子工序描述
               strList.Add("ZQMMES-ZBHGLB", dr["ZBHGLB"].ToString());//不合格品类别
               strList.Add("ZQMMES-ZSLDW", dr["ZSLDW"].ToString()); //审理单位	
               strList.Add("ZQMMES-ZLPH2", dr["ZLPH2"].ToString());//炉批号
               strList.Add("ZQMMES-ZPCH2", dr["ZPCH2"].ToString());// 机加批次号  	
               strList.Add("ZQMMES-ZLJLB", dr["ZLJLB"].ToString());//	零件类别
               strList.Add("ZQMMES-ZJX2", dr["ZJX2"].ToString());//型别
               strList.Add("ZQMMES-ZJGS", dr["ZJGS"].ToString());//加工总数
               strList.Add("ZQMMES-ZBHGPS", dr["ZBHGPS"].ToString());//不合格品数
               strList.Add("ZQMMES-ZBC", dr["ZBC"].ToString());//	版次
               strList.Add("ZQMMES-ZZRDW2", dr["ZZRDW2"].ToString());//责任单位
               strList.Add("ZQMMES-ZGD2", dr["ZGD2"].ToString());//工段
               strList.Add("ZQMMES-ZCLPH2", dr["ZCLPH2"].ToString());//材料牌号
               strList.Add("ZQMMES-QMGRP", dr["QMGRP"].ToString()); //	编码-代码组
               strList.Add("ZQMMES-QMCOD", dr["QMCOD"].ToString());//编码-代码
               strList.Add("ZQMMES-ZZTTXT", dr["ZZTTXT"].ToString());//主题长文本（缺陷文本）     
               strList.Add("ZQMMES-POSNR", dr["POSNR"].ToString());//缺陷-排序号
               strList.Add("ZQMMES-FEGRP", dr["FEGRP"].ToString());//缺陷-代码组
               strList.Add("ZQMMES-FECOD", dr["FECOD"].ToString());//缺陷-代码
               strList.Add("ZQMMES-FETXT", dr["FETXT"].ToString());//缺陷短文本描述
               strList.Add("ZQMMES-ZQXTXT", dr["ZQXTXT"].ToString());//行项目缺陷长文本
               strList.Add("RECORDID", dr["CONTAINERNONCONFORMINGINFOID"].ToString());//唯一标识
               
               //ADD BY YUXJ 20170615
               strList.Add("ZQMMES-QMNUM", dr["QMNUM"].ToString());
               strList.Add("ZQMMES-ZBHGDH", dr["ZBHGDH"].ToString());
               strList.Add("ZQMMES-ZSLJL", dr["ZSLJL"].ToString());
               strList.Add("ZQMMES-ZBZ2", dr["ZBZ2"].ToString());
               strList.Add("ZQMMES-ZYWLPC2", dr["ZYWLPC2"].ToString());
               strList.Add("ZQMMES-ZJYBH", dr["ZJYBH"].ToString());
               strList.Add("ZQMMES-ZSFGL", dr["ZSFGL"].ToString());


               string strXML = CreateXMLForNonconforming(strList);
               LogHelp.WriteLog("推送的xml"+strXML);
               ERPService.ErpAndAppSyncData mm = new ERPService.ErpAndAppSyncData();
               mm.ReqMsg = strXML;
               ERPService.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
               if (result != null)
               {
               string strMsg = "";
               strMsg = result.RespMsg;
               LogHelp.WriteLog(strMsg);
               string  strQMNUM = "";//反馈给我们的通知单号,更新到表中 add:Wangjh 20180423
               if (GetERPRcvXML(strMsg, ref strQMNUM))
               {
                   UpdateNonconformingIntegration(dr["CONTAINERNONCONFORMINGINFOID"].ToString(), strQMNUM);
                   OracleDAL.InsertSyncRecord(dr["CONTAINERNONCONFORMINGINFOID"].ToString(), m_cRecordType, "成功", 0);
               }
               else
               {
                   UpdateNonconformingIntegration(dr["CONTAINERNONCONFORMINGINFOID"].ToString(), strQMNUM);
                   OracleDAL.InsertSyncRecord(dr["CONTAINERNONCONFORMINGINFOID"].ToString(), m_cRecordType, strMsg, 1);
               }
               }
              
           }
       }

        /// <summary>
        /// 不合格品审理获取
        /// </summary>
        /// <returns></returns>
        private DataTable GetNonconforming()
        {
            try
            {
                string strTmp = @"SELECT T.*  FROM CONTAINERNONCONFORMINGINFO T 
                                 WHERE T.ISUSE = 0
                                   AND T.ISINTEGRATION = 1  ";

                DataSet myDS = OracleHelper.Query(strTmp);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("不合格品审理获取", e);
                return null;
            }
        }

        private void UpdateNonconformingIntegration(string nonconformingID, string strQMNUM)
        {
            string strSql = @"UPDATE CONTAINERNONCONFORMINGINFO SET ISINTEGRATION = 0";
            if (!string.IsNullOrWhiteSpace(strQMNUM))
                strSql += string.Format(" ,qmnum='{0}'", strQMNUM);
            strSql +=" WHERE CONTAINERNONCONFORMINGINFOID = :v_recordid";
            OracleParameter[] insertParam = new OracleParameter[1];

            insertParam[0] = new OracleParameter();
            insertParam[0].ParameterName = ":v_recordid";
            insertParam[0].OracleType = OracleType.VarChar;
            insertParam[0].Direction = ParameterDirection.Input;
            insertParam[0].Value = nonconformingID;

            int i = OracleHelper.ExecuteSql(strSql, insertParam);
        }

        private string CreateXMLForNonconforming(Dictionary<string, string> strList)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "ZQMF_MES_BHGPSL";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            string strData = "<ALCNRINFO>";
            foreach (KeyValuePair<string, string> _key in strList)
            {
                strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
            }
            strData += "</ALCNRINFO>";
            documentNode.AppendChild(doc.CreateCDataSection(strData));
            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetERPRcvXML(string strXML, ref string strQMNUM)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;
            string strDocument = doc.SelectSingleNode("RespMsg/document").InnerText;
            if (isSuccess == "true" || meaasge == "S")
            {
                string[] temp = strDocument.Split('：');
                if (temp.Length > 1)
                {
                    strQMNUM = temp[1];
                }
                return true; 
            }
            else
            {
                LogHelp.WriteLog(meaasge);
                return false;
            }
        }
        private const string m_cRecordType = "nonconforming";
    }
}
